package com.book.app.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.app.dao.BorrowDao;
import com.book.app.entity.Book;
import com.book.app.entity.Borrow;
import com.book.app.service.BookService;
import com.book.app.service.BorrowService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * (Borrow)表服务实现类
 *
 * @author wjy
 * @since 2021-09-22 08:48:13
 */
@Service("borrowService")
@Transactional
public class BorrowServiceImpl extends ServiceImpl<BorrowDao, Borrow> implements BorrowService {

    @Resource
    private BorrowDao borrowDao;
    @Resource
    private BookService bookService;

    @Override
    public List<Borrow> findPager(Integer page, Integer limit, String bname) {
        return borrowDao.findPager((page-1)*limit,limit ,bname);
    }

    @Override
    public boolean borrowBook(Borrow borrow) {
        Book book =bookService.getById(borrow.getBid()); //图书ID查询馆藏图书
        if(book.getQuantity()>=borrow.getQuantity()){ //馆藏数量大于等于借出数量
            book.setQuantity(book.getQuantity()-borrow.getQuantity()); //馆藏图书数量减去借出数量
            bookService.updateById(book);//更新图书馆藏库存
        }
        borrow.setOtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date()));
        return borrowDao.insert(borrow)>0;
    }

    @Override
    public boolean backBook(Borrow borrow) {
        Book book =bookService.getById(borrow.getBid()); //图书ID查询馆藏图书
        book.setQuantity(book.getQuantity()+borrow.getQuantity());
        bookService.updateById(book);//更新图书馆藏库存
        borrow.setStat(1);
        borrow.setItime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date()));
        return borrowDao.updateById(borrow)>0;
    }

    @Override
    public int counter(String bname) {
        return borrowDao.counter(bname);
    }

    @Override
    public List<Borrow> getBorrowCounter() {
        return borrowDao.getBorrowCounter();
    }
}

